import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
import {AppConfig} from '../config';
import {WindPowers} from '../entity/wind-powers.model';
import {InterceptorService} from './interceptor/interceptor-service';

@Injectable()
export class WindPowersService {
  private param = 'windPowers';

  private get url(): string {
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }


  constructor(private http: InterceptorService) {
  }

  getWindPowers(): Promise<WindPowers[]> {
    return this.http.get(this.url)
      .toPromise()
      .then(response => response.code === '200' ? response.data as WindPowers[] : [])
      .catch(this.handleError);
  }

  getWindPowersByModelId(modelId: number): Promise<WindPowers[]> {
    const url = `${this.url}/modelId/${modelId}`;
    return this.http.get(url)
      .toPromise()
      .then(response => response.code === '200' ? response.data as WindPowers[] : [])
      .catch(this.handleError);
  }

  getWindPowersBySchemeId(schemeId: number): Promise<WindPowers[]> {
    const url = `${this.url}/schemeId/${schemeId}`;
    return this.http.get(url)
      .toPromise()
      .then(response => response.code === '200' ? response.data as WindPowers[] : [])
      .catch(this.handleError);
  }

  create(windPower: WindPowers): Promise<WindPowers> {
    return this.http
      .post(this.url, JSON.stringify(windPower))
      .toPromise()
      .then(res => res.data)
      .catch(this.handleError);
  }

  update(windPower: WindPowers): Promise<WindPowers> {
    const url = `${this.url}`;
    // const url = `http://192.168.15.3:8585/webapi/v1/windPowers`;
    return this.http
      .put(url, JSON.stringify(windPower))
      .toPromise()
      .then(() => windPower)
      .catch(this.handleError);
  }

  delete(id: number): Promise<void> {
    const url = `${this.url}/${id}`;
    return this.http.delete(url)
      .toPromise()
      .then(() => null)
      .catch(this.handleError);
  }

  batchDelete(keyIds: number[]): Promise<boolean> {
    const apiUrl = `${this.url}?items=${keyIds}`;
    return this.http.delete(apiUrl)
      .toPromise()
      .then(response => {
        try {
          let result = response;
          switch (result.code) {
            case '200':
              return true;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          throw error;
        }

      })
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    // console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }
}


// WEBPACK FOOTER //
// ./src/app/service/wind-powers.service.ts
